package fregat.base.database;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Hashtable;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;


import fregat.base.util.Logger;
import fregat.base.util.XMLFilePath;

public class DBLink {
	private File linkFile;
	
	private Hashtable <DBConfigAttributes, String> attr;
	
	
	public DBLink (XMLFilePath linkConfigFileName) throws FileNotFoundException {
		attr = new Hashtable <DBConfigAttributes, String>();
		linkFile = linkConfigFileName.getFile();
	}
	
	public void readDBLink () throws ConfigurationInvalidException {
		try {
			Document doc = null;
			SAXBuilder builder = new SAXBuilder();
			doc = builder.build(linkFile);
			
			Element db = doc.getRootElement().getChild("database");
			if (db==null) {
				Exception e = new ConfigurationInvalidException ();
				Logger.getCategory("db").error("Could not find \"database\"-element in xml tree", e);
				throw e;
			}
			attr.put(DBConfigAttributes.DBSERVER, db.getAttributeValue("dbserver"));
			attr.put(DBConfigAttributes.DBPORT, db.getAttributeValue("dbport"));
			attr.put(DBConfigAttributes.DBNAME, db.getAttributeValue("dbname"));
			attr.put(DBConfigAttributes.DBUSER, db.getAttributeValue("dbuser"));
			attr.put(DBConfigAttributes.DBPASS, db.getAttributeValue("dbpass"));
			attr.put(DBConfigAttributes.DBINSTANCE, db.getAttributeValue("dbinstance"));
			attr.put(DBConfigAttributes.DBVENDOR, db.getAttributeValue("dbtype"));
		} 
		catch (IOException ioex) {
			Logger.getCategory("db").error("File " + linkFile.getAbsolutePath(), ioex);
			throw new ConfigurationInvalidException ();
		}
		catch (Exception e) {
			Logger.getCategory("db").error("File " + linkFile.getAbsolutePath(), e);
			throw new ConfigurationInvalidException ();
		}
	}
	
	public String get (DBConfigAttributes attr_) {
		return attr.get(attr_);
	}
	
	public enum DBConfigAttributes {
		DBSERVER, DBPORT, DBNAME, DBUSER, DBPASS, DBINSTANCE, DBTYPE, DBVENDOR
	}
	
	public class ConfigurationInvalidException extends Exception {
		
	}
	

}
